package start.demo01.datatype.json.entity.editor.jsonEditor;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import start.demo01.datatype.json.interfaces.JSONEditor;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

//驼峰下划线转换
public class JSONUnderlineEditor extends JSONEditor {

    //underline(true)
    public JSONUnderlineEditor(String args) {
        super(args);
    }

    {
        name = "UNDERLINE";
    }

    @Override
    protected void operationObject(JSONObject object, String key) {
//        JSONObject jsonObject = object.getJSONObject(key);
        return;
    }

    @Override
    protected void operationArray(JSONArray array, int index) {
        return;
    }

    @Override
    protected void operation(JSONObject object) {
        boolean bool = args.equals("true");
        underline(bool, object);
    }

    //下划线
    private static void underline(Boolean bool, JSONObject object) {
        LinkedList<Map.Entry<String, Object>> list=new LinkedList<>();
        Iterator<Map.Entry<String, Object>> iterator = object.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> next = iterator.next();
            iterator.remove();
            list.add(next);
        }
        for (Map.Entry<String, Object> entry : list) {
            String key = entry.getKey();
            if (bool)
                key = underline(key);
            else
                key = hump(key);
            object.put(key,entry.getValue());
        }
    }

    private static String hump(String key) {
        StringBuilder builder = new StringBuilder();
        char[] chars = key.toCharArray();
        boolean bool = false;
        for (char c : chars) {
            if (c == '_')
                bool = true;
            else if (bool) {
                builder.append(upper(c));//转大写
                bool = false;
            } else
                builder.append(c);
        }
        return builder.toString();
    }

    private static String underline(String key) {
        StringBuilder builder = new StringBuilder();
        char[] chars = key.toCharArray();
        for (char c : chars) {
            if (c >= 'A' && c <= 'Z')
                builder.append('_');
            builder.append(lower(c));
        }
        return builder.toString();
    }

    /**
     * A 65
     * a 97
     */
    private static char upper(char c) {
        if (c < 'a' || c > 'z')
            return c;
        return (char) (c - 32);
    }

    private static char lower(char c) {
        if (c < 'A' || c > 'Z')
            return c;
        return (char) (c + 32);
    }

}
